import { Router, Request, Response } from 'express';
import { FolderService } from '../services/FolderService';
import Joi from 'joi';

const router = Router();
const folderService = new FolderService();

// ==================== 验证中间件 ====================

const validateFolder = (req: Request, res: Response, next: any): void => {
  const schema = Joi.object({
    name: Joi.string().min(1).max(255).required(),
    parent_id: Joi.string().uuid().optional(),
    created_by: Joi.string().max(255).optional()
  });

  const { error } = schema.validate(req.body);
  if (error) {
    res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: error.details.map(detail => detail.message)
    });
    return;
  }

  next();
};

const validateFolderUpdate = (req: Request, res: Response, next: any): void => {
  const schema = Joi.object({
    name: Joi.string().min(1).max(255).optional(),
    parent_id: Joi.string().uuid().optional()
  });

  const { error } = schema.validate(req.body);
  if (error) {
    res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: error.details.map(detail => detail.message)
    });
    return;
  }

  next();
};

const validateSearchParams = (req: Request, res: Response, next: any): void => {
  const schema = Joi.object({
    keyword: Joi.string().max(255).optional(),
    parent_id: Joi.string().uuid().optional(),
    created_by: Joi.string().max(255).optional(),
    limit: Joi.number().integer().min(1).max(100).optional(),
    offset: Joi.number().integer().min(0).optional()
  });

  const { error } = schema.validate(req.query);
  if (error) {
    res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: error.details.map(detail => detail.message)
    });
    return;
  }

  next();
};

const validateBatchOperation = (req: Request, res: Response, next: any): void => {
  const schema = Joi.object({
    folder_ids: Joi.array().items(Joi.string().uuid()).min(1).max(50).required(),
    operation: Joi.string().valid('delete', 'move').required(),
    target_parent_id: Joi.string().uuid().optional(),
    force: Joi.boolean().optional()
  });

  const { error } = schema.validate(req.body);
  if (error) {
    res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: error.details.map(detail => detail.message)
    });
    return;
  }

  next();
};

// ==================== CRUD操作 ====================

// 创建文件夹
router.post('/', validateFolder, async (req: Request, res: Response): Promise<void> => {
  try {
    const folder = await folderService.createFolder(req.body);
    res.status(201).json({
      success: true,
      message: '文件夹创建成功',
      data: folder
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '创建文件夹失败',
      error: error.message
    });
  }
});

// 获取文件夹树形结构
router.get('/tree', async (_req: Request, res: Response): Promise<void> => {
  try {
    const tree = await folderService.getFolderTree();
    res.json({
      success: true,
      message: '获取文件夹树成功',
      data: tree
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取文件夹树失败',
      error: error.message
    });
  }
});

// 获取文件夹列表（支持搜索）
router.get('/', validateSearchParams, async (req: Request, res: Response): Promise<void> => {
  try {
    const {
      keyword,
      parent_id,
      created_by,
      limit = 20,
      offset = 0
    } = req.query;

    if (keyword) {
      // 搜索文件夹
      const result = await folderService.searchFolders(keyword as string, {
        parent_id: parent_id as string,
        created_by: created_by as string,
        limit: Number(limit),
        offset: Number(offset)
      });

      res.json({
        success: true,
        message: '搜索文件夹成功',
        data: result
      });
    } else {
      // 获取子文件夹
      const folders = await folderService.getChildFolders(parent_id as string);
      res.json({
        success: true,
        message: '获取文件夹列表成功',
        data: {
          folders,
          total: folders.length
        }
      });
    }
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取文件夹列表失败',
      error: error.message
    });
  }
});

// 获取单个文件夹详情
router.get('/:id', async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const folder = await folderService.getFolder(id);
    
    if (!folder) {
      res.status(404).json({
        success: false,
        message: '文件夹不存在'
      });
      return;
    }

    res.json({
      success: true,
      message: '获取文件夹详情成功',
      data: folder
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取文件夹详情失败',
      error: error.message
    });
  }
});

// 更新文件夹
router.put('/:id', validateFolderUpdate, async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const folder = await folderService.updateFolder(id, req.body);
    
    res.json({
      success: true,
      message: '文件夹更新成功',
      data: folder
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '更新文件夹失败',
      error: error.message
    });
  }
});

// 删除文件夹
router.delete('/:id', async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const { force } = req.query;
    
    await folderService.deleteFolder(id, { force: force === 'true' });
    
    res.json({
      success: true,
      message: '文件夹删除成功'
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '删除文件夹失败',
      error: error.message
    });
  }
});

// ==================== 文件夹管理操作 ====================

// 获取文件夹内容（包含子文件夹和脚本）
router.get('/:id/contents', async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const contents = await folderService.getFolderContents(id);
    
    res.json({
      success: true,
      message: '获取文件夹内容成功',
      data: contents
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取文件夹内容失败',
      error: error.message
    });
  }
});

// 移动文件夹
router.patch('/:id/move', async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const { parent_id } = req.body;
    
    const folder = await folderService.moveFolder(id, parent_id);
    
    res.json({
      success: true,
      message: '文件夹移动成功',
      data: folder
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '移动文件夹失败',
      error: error.message
    });
  }
});

// 重命名文件夹
router.patch('/:id/rename', async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const { name } = req.body;
    
    if (!name || typeof name !== 'string') {
      res.status(400).json({
        success: false,
        message: '文件夹名称不能为空'
      });
      return;
    }
    
    const folder = await folderService.renameFolder(id, name);
    
    res.json({
      success: true,
      message: '文件夹重命名成功',
      data: folder
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '重命名文件夹失败',
      error: error.message
    });
  }
});

// 复制文件夹
router.post('/:id/copy', async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const { name, parent_id, created_by } = req.body;
    
    if (!name || typeof name !== 'string') {
      res.status(400).json({
        success: false,
        message: '文件夹名称不能为空'
      });
      return;
    }
    
    const folder = await folderService.copyFolder(id, name, parent_id, created_by);
    
    res.status(201).json({
      success: true,
      message: '文件夹复制成功',
      data: folder
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '复制文件夹失败',
      error: error.message
    });
  }
});

// 获取文件夹路径
router.get('/:id/path', async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const path = await folderService.getFolderPath(id);
    
    res.json({
      success: true,
      message: '获取文件夹路径成功',
      data: { path }
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取文件夹路径失败',
      error: error.message
    });
  }
});

// 获取文件夹统计信息
router.get('/:id/stats', async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const stats = await folderService.getFolderStats(id);
    
    res.json({
      success: true,
      message: '获取文件夹统计成功',
      data: stats
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取文件夹统计失败',
      error: error.message
    });
  }
});

// ==================== 批量操作 ====================

// 批量操作文件夹
router.post('/batch', validateBatchOperation, async (req: Request, res: Response): Promise<void> => {
  try {
    const { folder_ids, operation, target_parent_id, force } = req.body;
    
    const result = await folderService.batchOperateFolders(folder_ids, operation, {
      target_parent_id,
      force
    });
    
    res.json({
      success: true,
      message: `批量${operation === 'delete' ? '删除' : '移动'}操作完成`,
      data: result
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '批量操作失败',
      error: error.message
    });
  }
});

// ==================== 权限管理 ====================

// 获取文件夹权限（占位符 - 未来实现）
router.get('/:id/permissions', async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    
    // 目前返回默认权限，未来可以扩展为真实的权限管理
    const permissions = {
      folder_id: id,
      owner: 'system',
      permissions: {
        read: true,
        write: true,
        delete: true,
        manage: true
      },
      shared_with: [],
      created_at: new Date().toISOString()
    };
    
    res.json({
      success: true,
      message: '获取文件夹权限成功',
      data: permissions
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: error.message || '获取文件夹权限失败',
      error: error.message
    });
  }
});

// 更新文件夹权限（占位符 - 未来实现）
router.put('/:id/permissions', async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const { permissions, shared_with } = req.body;
    
    // 目前只是返回成功响应，未来可以实现真实的权限更新
    res.json({
      success: true,
      message: '文件夹权限更新成功',
      data: {
        folder_id: id,
        permissions: permissions || {
          read: true,
          write: true,
          delete: true,
          manage: true
        },
        shared_with: shared_with || [],
        updated_at: new Date().toISOString()
      }
    });
  } catch (error: any) {
    res.status(400).json({
      success: false,
      message: error.message || '更新文件夹权限失败',
      error: error.message
    });
  }
});

export default router;